package sdufe.lele.controller;

import org.apache.shiro.util.ThreadContext;
import org.springframework.web.bind.annotation.*;
import sdufe.lele.annotation.authToken;
import sdufe.lele.dao.BrokerMapper;
import sdufe.lele.model.Broker;
import sdufe.lele.result.ApiResult;
import sdufe.lele.result.MapResult;
import sdufe.lele.result.Result;


import javax.annotation.Resource;
import java.util.List;

/**
 * Created by olivia on 4/13/2017.
 */
@RequestMapping("/broker")
@RestController
public class BrokerController {

    @Resource
    private BrokerMapper brokerMapper;


    @GetMapping("/selectBroker.do")
    @authToken
    public Result getBroker() {
        MapResult mapResult = new MapResult();
        String phone = (String) ThreadContext.get("user-phone");
        List<Broker> brokerList;
        if (phone.equals("admin")) {
            brokerList = brokerMapper.selectAll();
        } else {
            brokerList = brokerMapper.selectAllByPhone(phone);
        }


        mapResult.put("brokerName", brokerList);
        return mapResult;

    }

    @PutMapping("/updateBroker.do")
    @authToken
    public Result updateBroker(@RequestParam(name = "oldBrokerName") String oldBrokerName,
                               @RequestParam(name = "newBrokerName") String newBrokerName) {
        ApiResult apiResult = new ApiResult();

        brokerMapper.updateByName(oldBrokerName, newBrokerName);
        return apiResult;

    }

    @PostMapping("/insertBroker.do")
    @authToken
    public Result insertBroker(@RequestParam(name = "brokerName") String brokerName) {
        ApiResult apiResult = new ApiResult();

        Broker broker = new Broker(brokerName, (String) ThreadContext.get("user-phone"));
        brokerMapper.insertSelective(broker);
        return apiResult;

    }

    @DeleteMapping("/deleteBroker.do")
    @authToken
    public Result deleteBroker(@RequestParam(name = "brokerName") String brokerName) {
        ApiResult apiResult = new ApiResult();

        brokerMapper.deleteByName(brokerName);
        return apiResult;
    }


}
